using System;
using EasyDapr.Domain;
using EasyDapr.Infrastructure.Response;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace EasyDapr.Infrastructure.Attribute
{
    /// <summary>
    /// api异常统一处理过滤器
    /// 系统级别异常 500 应用级别异常200
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            context.Result = BuildExceptionResult(context.Exception);
            base.OnException(context);
        }

        /// <summary>
        /// 包装处理异常格式
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        private static JsonResult BuildExceptionResult(Exception ex)
        {
            // 如果是应用程序业务级异常，则为200
            var statusCode = 200;
            string message;
            var innerMessage = "";
            //应用程序业务级异常
            if (ex is CoreException || ex is ApplicationException)
            {
                message = ex.Message;
            }
            else
            {
                statusCode = 500;
                // exception 系统级别异常，不直接明文显示的
                message = "服务器发生异常";
                innerMessage = ex.Message;
            }

            if (ex.InnerException != null && ex.Message != ex.InnerException.Message)
            {
                innerMessage += "," + ex.InnerException.Message;
            }

            return new JsonResult(new ApiResult<object>
            {
                InnerMessage = innerMessage,
                Message = message,
                Success = false,
                StatusCode = statusCode,
                Data = ""
            });
        }
    }
}